(function() {
    angular.module('app', ['ui.router', 'ngAnimate', 'ngSanitize', 'ngTouch', 'atomic-notify', 'darthwade.dwLoading', 'angularjs-datetime-picker', 'ng-pagination', 'pasvaz.bindonce', 'angularBootstrapNavTree', 'ui.bootstrap']);
})();
//config
(function() {
    angular.module('app').config(appConfig);



    appConfig.$inject = ['atomicNotifyProvider'];

    function appConfig(atomicNotifyProvider) {
        //分页插件设置模板html
        // paginationTemplateProvider.setPath('lib/dirPagination/dirPagination.tpl.html');

        // RollbarProvider.init({
        //     accessToken: "2afb66965bc846a38a021a9c5bd6ec87",
        //     captureUncaught: true,
        //     payload: {
        //         environment: "test"
        //     }

        // });

        atomicNotifyProvider.setDefaultDelay(3000);


        // angular.module('app').run(['$http',function($http) {
        //     // $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
        //     $http.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
        // }]);
    }

})();

// route
(function() {
    angular.module('app').config(routerConfig);

    routerConfig.$inject = ['$urlRouterProvider', '$stateProvider', '$locationProvider'];

    function routerConfig($urlRouterProvider, $stateProvider, $locationProvider) {


        $urlRouterProvider.otherwise('/industry');

        $stateProvider.state('industry', {
            url: '/industry',
            templateUrl: 'app/controllers/industry.controller/industry.controller.html',
            controller: 'industryCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('brand', {
            url: '/brand',
            templateUrl: 'app/controllers/brand.controller/brand.controller.html',
            controller: 'brandCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('shop', {
            url: '/shop',
            templateUrl: 'app/controllers/shop.controller/shop.controller.html',
            controller: 'shopCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('product', {
            url: '/product',
            templateUrl: 'app/controllers/product.controller/product.controller.html',
            controller: 'productCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('monitor', {
            url: '/monitor',
            templateUrl: 'app/controllers/monitor.controller/monitor.controller.html',
            controller: 'monitorCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('newProduct', {
            url: '/newProduct',
            templateUrl: 'app/controllers/newProduct.controller/newProduct.controller.html',
            controller: 'newProductCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('attr', {
            url: '/attr',
            templateUrl: 'app/controllers/attr.controller/attr.controller.html',
            controller: 'attrCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('words', {
            url: '/words',
            templateUrl: 'app/controllers/words.controller/words.controller.html',
            controller: 'wordsCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('redNet', {
            url: '/redNet',
            css: {
                preload: true,
                href: 'app/controllers/redNet.controller/redNet.controller.css'
            },
            templateUrl: 'app/controllers/redNet.controller/redNet.controller.html',
            controller: 'redNetCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('setting', {
            url: '/setting',
            templateUrl: 'app/controllers/setting.controller/setting.controller.html',
            controller: 'settingCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('manage', {
            url: '/manage',
            css: {
                href: "app/controllers/manage.controller/manage.controller.css"
            },
            templateUrl: 'app/controllers/manage.controller/manage.controller.html',
            controller: 'manageCtrl',
            controllerAs: 'vm',
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        }).state('price', {
            url: '/price', 
            views:{
                "":{
                    templateUrl: 'app/controllers/monitorPrice.controller/monitorPrice.controller.html'
                },
                "model@price":{
                    template: '<manage-model-component></manage-model-component>'
                },
                "link@price":{
                    template: 'app/controllers/monitorPrice.controller/monitorPrice.controller.html'
                }
            }, 
            
            resolve: {
                user: ['userService', function(userService) {
                    return userService.getUser();
                }]
            }
        });
    }


    angular.module('app').factory('userService', userService);

    userService.$inject = ['util', '$q', '$rootScope'];

    function userService(util, $q, $rootScope) {

        var user = {};

        return {
            user: userReturn,
            getUser: _getUser,
            expired: _expired
        }

        function userReturn() {

            return user;
        }

        function _getUser() {

            var defer = $q.defer();

            if ($.isEmptyObject(user)) {


                util.$get({ url: '/qbmf/api/user', ignoreLoadingBar: true }).then(function(resp) {


                    $rootScope.userInfo = resp.value;

                    /*var version = resp.value.version;


                    if (version.indexOf('standard') != -1) {

                        $rootScope.userInfo.verInfo = "标准版";
                        $rootScope.userInfo.ver = "standard";

                    } else if (version.indexOf('pro') != -1) {

                        $rootScope.userInfo.verInfo = "大师版";
                        $rootScope.userInfo.ver = "pro";

                    } else {

                        $rootScope.userInfo.verInfo = "免费版";
                        $rootScope.userInfo.ver = "free";

                    }*/


                    defer.resolve(resp.value);

                }, function(err) {

                    defer.reject();

                });

            } else {

                console.log('user:' + user);

                defer.resolve(user);

            }



            return defer.promise;
        }


        function _expired() {
            //云起
            if (user.channel == '1') {
                $window.location.href = '/marketconditions/user/shopexLogin.htm'
            } else {
                $window.location.href = 'login.html';
            }
        }
    }

})();

//filter
(function() {
    angular.module('app').filter('bigNum', function() {
        return function(input) {
            if (!/^(\d|\.)+$/g.test(input)) {
                return input;
            }

            try {
                input = Number(input);
            } catch (e) {
                return input;
            }

            var num = Number(input);


            if (num < 10000) {
                return num;
            } else {
                num = Number(input.toFixed(0));
            }
            var len = String(num).length;

            switch (len) {
                case 5:
                    return (num / 10000).toFixed(2) + '万';
                case 6:
                    return (num / 10000).toFixed(2) + '万';
                case 7:
                    return (num / 10000).toFixed(2) + '万';
                case 8:
                    return (num / 10000).toFixed(2) + '万';
                case 9:
                    return (num / 100000000).toFixed(2) + '亿';
                case 10:
                    return (num / 100000000).toFixed(2) + '亿';
                case 11:
                    return (num / 100000000).toFixed(2) + '亿';
                case 12:
                    return (num / 100000000).toFixed(2) + '亿';
            }

            return num;
        }
    });

    angular.module('app').filter('year', function() {
        return function(input) {
            var year; //input 2017-04-13 17:03:00
            if (input && input !== "") {

                year = input.slice(0, 4);
            }

            return year;
        }
    });

    angular.module('app').filter('month', function() {
        return function(input) {
            var month; //input 2017-04-13 17:03:00
            if (input && input !== "") {

                month = input.slice(5, 7);
            }

            return month;
        }
    });

    angular.module('app').filter('day', function() {
        return function(input) {
            var day; //input 2017-04-13 17:03:00
            if (input && input !== "") {

                day = input.slice(8, 10);
            }

            return day;
        }
    });

    angular.module('app').filter('shopType', function() {
        return function(input) {
            // console.log(input);
            switch (input) {
                case '商城':
                    return '天猫';
                    break;
                case 'C店':
                    return '淘宝';
                    break;
                case '天猫国际':
                    return input;
                    break;
                case '全球购':
                    return input;
                    break;

                default:
                    return input;
                    break;
            }

        }
    });

    angular.module('app').filter('highlight', ['$sce', function($sce) {

        return function(text, phrase) {
            // console.log("text:"+text+"  phrase:"+phrase);
            if (phrase) text = text.replace(new RegExp('(' + phrase + ')', 'gi'),
                '<span class="highlight">$1</span>')

            return $sce.trustAsHtml(text)

            /*return a && (b || angular.isNumber(b)) ? 
            (
                a = a.toString(),
                b = b.toString(), 
                c ? a.split(b).join('<span class="highlight">' + b + "</span>") : a.replace(new RegExp(b, "gi"), '<span class="highlight">$&</span>')
            ) : a*/
        }
    }]);
})();

//util
(function() {
    angular.module('app').factory('util', util);

    util.$inject = ['$http', '$q', '$rootScope', '$window'];

    function util($http, $q, $rootScope, $window) {
        return {
            sourceApi: _sourceApi,
            $get: _get,
            $post: _post,
            $broadcast: _broadcast,
            $on: _on,
            $localStorage: _localStorage,
            bigNumFormat: _bigNumFormat,
            catNameFormat: _catNameFormat,
            historyFormat: _historyFormat,
            shopLevelFormat: _shopLevelFormat,
            dateFormat: _dateFormat,
            extend: _extend,
            isEmpty: _isEmpty,
            //user
            returnUserIndustryType: _returnUserIndustryType,
            returnUserIndustry: _returnIndustry
        }

        function _sourceApi() {

            var host = window.location.hostname;

            var config;

            switch (host) {
                case 'qbmf.trenddata.cn':

                    config = {
                        theme: 'theme_default',
                        icon: 'http://trendata.oss-cn-hangzhou.aliyuncs.com/marketconditions/favicon.ico',
                        title: '情报魔方',
                        logo: 'http://trendata.oss-cn-hangzhou.aliyuncs.com/marketconditions/logo.png'
                    };

                    break;
                case 'shop.630game.com':
                    config = {
                        theme: 'theme_ds',
                        icon: 'http://trendata.oss-cn-hangzhou.aliyuncs.com/marketconditions/icon.png',
                        title: '电商先生',
                        logo: 'http://trendata.oss-cn-hangzhou.aliyuncs.com/marketconditions/icon.png'
                    };

                    break;
                case 'esm.fenxiao8.com':

                    config = {
                        theme: 'theme_pp',
                        icon: 'http://121.41.160.43:30001/marketconditions/assets/img/pingpu.png',
                        title: '品谱大数据',
                        logo: 'http://121.41.160.43:30001/marketconditions/assets/img/pingpu.png'
                    };

                    break;
                case 'www.hzbigdate.com':

                    config = {
                        theme: 'theme_pp',
                        icon: 'http://121.41.160.43:30001/marketconditions/assets/img/pingpu.png',
                        title: '品谱大数据',
                        logo: 'http://121.41.160.43:30001/marketconditions/assets/img/pingpu.png'
                    };

                    break;
                case 'qzt.sinoac.org':

                    config = {
                        theme: 'theme_qzt',
                        icon: 'http://qzt.sinoac.org/assets/img/qzt/qzt_ico.png',
                        title: '企智通',
                        logo: 'http://121.41.160.43:30001/marketconditions/assets/img/pingpu.png'
                    };

                    break;

                default:

                    config = {
                        theme: 'theme_default',
                        icon: 'http://trendata.oss-cn-hangzhou.aliyuncs.com/marketconditions/favicon.ico',
                        title: '情报魔方',
                        logo: 'http://trendata.oss-cn-hangzhou.aliyuncs.com/marketconditions/logo.png'
                    };

                    break;
            }

            //title
            if (document.title === "") {
                document.title = config.title;
            }

            try {
                //link icon
                document.querySelector('link[rel=icon]').href = config.icon;
            } catch (oException) {

            }

            return config;

        }

        function _get(param) {

            if (!param instanceof Object || !param.url) {
                return;
            }
            var defer = $q.defer();



            $http({
                method: 'GET',
                url: param.url,
                params: param.data || {},
                headers: {
                    'Accept': 'application/json, text/javascript, */*'
                }
            }).then(function(resp) {
                var resp = resp.data;

                // console.log(resp);

                if (resp.code === 0) {

                    defer.resolve(resp);

                } else {
                    defer.reject(resp);

                    if (resp.value == "session expire") {

                        console.log('user is not login');
                        $window.location.href = "login.html";
                        return;
                    }

                }



            }, function(err) {
                var resp = err.data;
                // console.log(err);

                defer.reject(err);


            });

            return defer.promise;
        }

        function _post(param) {
            if (!param instanceof Object || !param.url) {
                return;
            }

            var defer = $q.defer();
            //{url:xx:data:{xx:xx}}          
            $http({
                method: 'post',
                url: param.url,
                data: param.data,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                }
            }).then(function(resp) {

                var resp = resp.data;
                if (resp.code === 0) {
                    defer.resolve(resp);
                } else {
                    defer.reject(resp);

                    if (resp.value == "session expired") {
                        $window.location.href = "login.html";
                        return;
                    }
                }
            }, function(err) {
                var err = err.data;

                defer.reject(err);
            });

            return defer.promise;
        }

        function _broadcast(ev, data) {
            $rootScope.$emit(ev, data);
        }

        function _on(scope, ev, callback) {
            if (!scope.EVENT_OFF) {
                scope.EVENT_OFF = [];
            }
            console.log('is $on:' + eventName);
            scope.EVENT_OFF[eventName] = $rootScope.$on(ev, callback);
            scope.$on('$destroy', function() {
                // console.log(scope);
                for (var i in scope.EVENT_OFF) {
                    console.log('destory:' + i);
                    scope.EVENT_OFF[i]();
                }
            });

        }

        function _localStorage() {



            return {
                set: _set,
                delete: _delete,
                get: _get,
                has: _has
            };


            function _set(key, value) {
                if (typeof value != 'string') {

                    value = JSON.stringify(value);
                }

                try {
                    $window.localStorage.setItem(key, value);
                } catch (oException) {
                    if (oException.name == 'QuotaExceededError') {
                        console.log('超出本地存储限额！');
                        //如果历史信息不重要了，可清空后再设置
                        $window.localStorage.clear();
                        $window.localStorage.setItem(key, value);
                    }
                }
            }

            function _delete(key) {

                if (this.has(key)) {
                    $window.localStorage.removeItem(key);
                } else {
                    console.log('无此存储键值对：' + key);
                }


            }


            function _get(key) {

                var item = $window.localStorage.getItem(key);

                try {
                    item = JSON.parse(item);
                } catch (oException) {
                    console.log(item);
                    console.log(oException.name);

                }

                return item;
            }

            function _has(key) {

                if ($window.localStorage.getItem(key) === null) {
                    return false;
                } else {
                    return true;
                }
            }

        }

        function _bigNumFormat(num) {



            if (num < 10000) {
                return num;
            }

            num = Number(Number(num).toFixed(0));

            var len = String(num).length;

            switch (len) {
                case 5:
                    return (num / 10000).toFixed(2) + '万';
                case 6:
                    return (num / 10000).toFixed(2) + '万';
                case 7:
                    return (num / 10000).toFixed(2) + '万';
                case 8:
                    return (num / 10000).toFixed(2) + '万';
                case 9:
                    return (num / 100000000).toFixed(2) + '亿';
                case 10:
                    return (num / 100000000).toFixed(2) + '亿';
                case 11:
                    return (num / 100000000).toFixed(2) + '亿';
                case 12:
                    return (num / 100000000).toFixed(2) + '亿';
            }

            return num;
        }


        function _catNameFormat(catName) {
            if (catName == '/') {
                return "全网";
            } else if (catName.indexOf('--') == -1) {
                return catName;
            } else {
                return catName.split('--')[catName.split('--').length - 1];
            }
        }

        function _historyFormat(stringHistory) {
            var x = [];
            var y = [];
            if (stringHistory.length > 0) {
                //'2017-01-16=83966' 一条记录            
                if (stringHistory.indexOf(';') == -1) {
                    var temp = stringHistory.split('=');
                    x.push(temp[0]);
                    y.push(temp[1]);
                } else {
                    //多条记录
                    var arr = stringHistory.split(';');
                    for (var k in arr) {
                        var temp = arr[k].split('=');
                        x.push(temp[0]);
                        y.push(temp[1]);
                    }
                }
            }

            return {
                x: x,
                y: y
            }
        }


        function _shopLevelFormat(shop) {
            if (shop.shopLevel >= 1 && shop.shopLevel <= 5) {
                shop.shopLevelType = 1;
            } else if (shop.shopLevel >= 6 && shop.shopLevel <= 10) {
                shop.shopLevelType = 2;
            } else if (shop.shopLevel >= 11 && shop.shopLevel <= 15) {
                shop.shopLevelType = 3;
            } else {
                shop.shopLevelType = 4;
            }

            shop.shopLevel = (shop.shopLevel - 1) % 5 + 1;
            shop.shopLevels = new Array(shop.shopLevel);

            if (shop.sellAmount == 0) {
                shop.avgPrice = 0;
            } else {
                shop.avgPrice = (shop.sellMoney / shop.sellAmount).toFixed(2) + '元';
            }

            return shop;
        }


        function _dateFormat(date) {

            var setTime = angular.isString(date) ? date : date.toString();

            return setTime.substring(0, 10);

        }


        function _extend(dst, src) {

            console.log(src);

            for (var i in dst) {

                for (var j in src) {

                    //查找到相同的数据项，替换
                    if (i === j) {
                        // console.log(i +" "+ dst[i]);console.log(j+" "+src[j]);
                        dst[i] = src[j];
                        break;
                    }
                }

            }

            return dst;
        }

        function _isEmpty(obj) {

            if (typeof obj !== "object") {
                console.log('isEmpty function argument is not obejct');
            } else {
                var bool = false;
                for (var i in obj) {

                    if (obj[i] !== '') {

                        bool = true;
                    } else {
                        continue;
                    }
                }

                i = null;

                return bool;

            }


        }

        function _returnIndustry(user) {

            var version = user.version;

            var itemLevel1Category = user.itemLevel1Category;



            var industry;

            if (version.indexOf('v1') != -1) { //全行业

                industry = '全行业';

                user.industry_type = 'all';

            } else if (version.indexOf('v2') != -1) { //多行业

                if (typeof itemLevel1Category == 'undefined' || itemLevel1Category.length == 0) {
                    industry = "";
                } else {
                    var arry = itemLevel1Category.split(';');

                    industry = [];

                    for (var i in arry) {
                        industry.push(arry[i].split('--')[1]);
                    }


                }

                user.industry_type = 'mutil';
            } else {

                if (itemLevel1Category == null || itemLevel1Category.length == 0) {
                    industry = "";
                } else {
                    industry = itemLevel1Category.split('--')[1];
                }


                user.industry_type = 'singel';
            }

            return industry;
        }


        function _returnUserIndustryType(user) {

            var version = user.version;
            var type;

            if (version.indexOf('v1') != -1) { //全行业

                type = 'all';
            } else if (version.indexOf('v2') != -1) { //多行业

                type = 'multi';
            } else {

                type = 'singel';
            }

            return type;

        }
    }

})();
